package com.serve.oa.common.exception;

import com.serve.oa.common.lang.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.AuthorizationException;
import org.flowable.common.engine.api.FlowableObjectNotFoundException;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

	//

	// 实体校验异常捕获

	//

	@ResponseStatus(HttpStatus.OK)
	@ExceptionHandler(value = FlowableObjectNotFoundException.class)
	public Result handler(FlowableObjectNotFoundException e) {


		System.out.println(e.getMessage());
		return Result.fail(400,"该流程已经完成了，没有图片");
	}

	@ResponseStatus(HttpStatus.OK)
	@ExceptionHandler(value = MethodArgumentNotValidException.class)
	public Result handler(MethodArgumentNotValidException e) {

		BindingResult result = e.getBindingResult();
		ObjectError objectError = result.getAllErrors().stream().findFirst().get();

		log.error("实体校验异常：----------------{}", objectError.getDefaultMessage());
		return Result.fail(400,objectError.getDefaultMessage());
	}

	@ResponseStatus(HttpStatus.OK)
	@ExceptionHandler(value = IllegalArgumentException.class)
	public Result handler(IllegalArgumentException e) {
		log.error("Assert异常：----------------{}", e.getMessage());
		return Result.fail(e.getMessage());
	}

	@ResponseStatus(HttpStatus.OK)
	@ExceptionHandler(value = RuntimeException.class)
	public Result handler(RuntimeException e) {
		log.error("运行时异常：----------------{}", e.getMessage());
		return Result.fail(e.getMessage());
	}


	@ResponseStatus(HttpStatus.OK)
	@ExceptionHandler(value = AuthenticationException.class)
	public Result handler(AuthenticationException e) {
		log.error("没权限", e.getMessage());
		return Result.fail(e.getMessage());
	}


	@ResponseStatus(HttpStatus.OK)
	@ExceptionHandler(value = AuthorizationException.class)
	public Result handler(AuthorizationException e) {
		log.error("接口没权限", e.getMessage());
		return Result.fail(403,"你没有权限");
	}
}
